import { Descriptions, message, Skeleton, Empty, Modal, Table, Tooltip } from 'antd';
import { useEffect } from 'react';
import { QaCasePlanStatus } from './index'
import UserBrief from '@/components/UserBrief'
import ArrayUtils from '@/utils/ArrayUtils'
import { now } from '@/utils/dateUtils'
import EditAble from '@/components/EditAble'
import styles from './style.less'
import { useState } from 'react';
import { PROJECT_CASE_PLAN, PROJECT_CASE_PLAN_ENUM } from '@/consts/project'
import TextButton from '@/components/TextButton';
import ActionDropdown from '@/components/ActionDropdown';
import QaCasePlanRelCaseEditModal from './QaCasePlanRelCaseEditModal';
import QaCaseDetailModal from '../QaCaseList/QaCaseDetailModal';
import { update, getDetail, getBrief } from '@/services/project/casePlan'
import { QuestionCircleOutlined } from '@ant-design/icons'
import { connect } from 'umi';


export const ConfirmStatus = ({ confirmStatus }) => {
    return confirmStatus === 1 ? <span style={{ color: "#73d13d" }}>是</span> : '否';
}

const QaCasePlanDetal = (props) => {
    const {
        projectId,
        dispatch,
        casePlanId,
        permission = {
            edit: true
        },
        casePlanData,
        onDetailChange,
        myUserInfo
    } = props


    useEffect(() => {
        getCasePlanDetail()
    }, [casePlanData])



    const [casePlanDetail, setCasePlanDetail] = useState({})
    const [casePlanRelCaseModalVisiable, setCasePlanRelCaseModalVisiable] = useState(false)
    const [casePlanDetailList, setCasePlanDetailList] = useState([])
    const [selectCasePlanDetail, setSelectCasePlanDetail] = useState({});
    const [qaCaseDetailVisiable, setQaCaseDetailVisiable] = useState(false)

    const updateUser = (userId, user) => {
        updateCasePlan({
            userId: userId
        })
        casePlanDetail.userId = userId;
        casePlanDetail.user = user;
        setCasePlanDetail({ ...casePlanDetail })
    }


    const updateProjectStatus = (status) => {
        let data = {
            status: status
        }
        if (status === PROJECT_CASE_PLAN_ENUM.COMPLETE) {
            data.endDate = now();
        }
        updateCasePlan(data)
        setCasePlanDetail({
            ...casePlanDetail,
            ...data
        })

    }

    const updateName = (name) => {
        updateCasePlan({
            name: name
        })
        casePlanDetail.name = name;
        setCasePlanDetail({ ...casePlanDetail })
    }

    const updateCasePlan = (data) => {
        update(projectId, casePlanData.projectQaItemId, casePlanId, data)
            .then((result) => {
                if (result.success) {
                    message.success("保存成功！")
                }
                if (onDetailChange) {
                    getCasePlanBrief()
                }
            })
    }


    const getCasePlanDetail = () => {
        getDetail(projectId, casePlanData.projectQaItemId, casePlanId)
            .then(({ data }) => {
                setCasePlanDetail(data)
                setCasePlanDetailList((data && data.casePlanDetailList) || [])
            })
    }

    const getCasePlanBrief = () => {
        getBrief(projectId, casePlanData.projectQaItemId, casePlanId)
            .then(({ data }) => {
                setCasePlanDetail(data)
                onDetailChange(data)
            })
    }

    if (!casePlanId) {
        return <div className={styles.casePlanDetail}><Empty></Empty></div>
    }

    if (!casePlanDetail) {
        return <div className={styles.casePlanDetail}><Skeleton></Skeleton></div>
    }

    const renderTitle = (item) => {
        if (!item.projectQaCase) {
            return <TextButton type="danger"> 用例已被删除</TextButton>
        }
        if (item.projectQaCase.moduleName) {
            return `【${item.projectQaCase.moduleName}】 ${item.projectQaCase.name}`
        }
        return ` ${item.projectQaCase.name}`
    }


    const columns = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            fixed: 'left',
            ellipsis: {
                showTitle: true,
            },
            render: (text, record) => renderTitle(record)
        },
        {
            title: '是否执行',
            dataIndex: 'isExecute',
            ellipsis: true,
            key: 'isExecute',
            width: "80px",
            render: (text, record) => <ConfirmStatus confirmStatus={record.isExecute}></ConfirmStatus>
        },
        {
            title: <Tooltip title="成功数/失败数">执行结果 <QuestionCircleOutlined /></Tooltip>,
            dataIndex: 'executeResult',
            ellipsis: true,
            key: 'executeResult',
            width: "100px",
            render: (text, record) => record.isExecute ? `${record?.successCnt || 0}/${record?.failedCnt || 0}` : ''
        },
        {
            title: '执行人',
            dataIndex: 'userId',
            ellipsis: true,
            key: 'userId',
            width: "140px",
            render: (text, record) => record.user && <UserBrief user={record.user} />
        },
        {
            title: (<div onClick={() => {
                setCasePlanRelCaseModalVisiable(true)
            }} style={{
                float: "right"
            }}>
                <a >修改用例清单</a>
            </div>),
            dataIndex: 'userId',
            ellipsis: true,
            key: 'userId',
            width: "96px",
            align: "center",
            render: (text, record) => {
                return <div style={{ display: "inline-flex", alignItems:"center" }}>
                    {record.projectQaCase && <TextButton type="primary" onClick={() => {
                        setSelectCasePlanDetail(record);
                        setQaCaseDetailVisiable(true)
                    }}
                    >执行</TextButton>}

                    <ActionDropdown
                        icon="more"
                        actions={[<TextButton type="danger" onClick={() => {
                            if (record.isExecute) {
                                message.error("已执行用例不允许删除")
                                return
                            }
                        }}
                        >删除</TextButton>]}
                    />
                </div>

            }
        },
    ]

    const onExecuteComplete = (result) => {
        setQaCaseDetailVisiable(false);
        console.log(result)
        let qaCaseDetailList = casePlanDetailList.map((item) => {
            if (item.id === result.id) {
                return {
                    ...item,
                    ...result,
                    userId: myUserInfo.id,
                    user: myUserInfo,
                }
            }
            return item
        })
        // console.log(qaCaseDetailList)
        setCasePlanDetailList(qaCaseDetailList)
    }

    return (
        <div className={styles.casePlanDetail}>
            <Descriptions size="small" column={2}>
                <Descriptions.Item span={2}>
                    <EditAble permission={permission}
                        value={casePlanDetail.name}
                        onSave={updateName}
                        type="input">
                        <h1>{casePlanDetail.name}</h1>
                    </EditAble>
                </Descriptions.Item>
                <Descriptions.Item label="负责人">
                    <EditAble permission={permission}
                        value={casePlanDetail.userId}
                        editComponentProps={{
                            projectId: projectId,
                            defaultOpen: true
                        }}
                        onSave={updateUser}
                        type="userSelect">
                        <UserBrief user={casePlanDetail.user}></UserBrief>
                    </EditAble>
                </Descriptions.Item>
                <Descriptions.Item label="状态">
                    <EditAble permission={permission}
                        value={casePlanDetail.status}
                        editComponentProps={{
                            options: ArrayUtils.jsonToArray(PROJECT_CASE_PLAN).map(item => {
                                return { value: item.key, label: item.value.name }
                            }),
                            defaultOpen: true
                        }}
                        onSave={updateProjectStatus}
                        type="select">
                        <QaCasePlanStatus status={casePlanDetail.status}></QaCasePlanStatus>
                    </EditAble>
                </Descriptions.Item>
                <Descriptions.Item label="开始时间">
                    {casePlanDetail.startDate || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="结束时间">
                    {casePlanDetail.endDate || '-'}
                </Descriptions.Item>
                <Descriptions.Item>
                    <Table
                        columns={columns}
                        rowKey="id"
                        dataSource={casePlanDetailList}
                        loading={!casePlanDetailList}
                        size="small"
                    >
                    </Table>
                </Descriptions.Item>
            </Descriptions >
            <QaCasePlanRelCaseEditModal
                projectId={projectId}
                projectQaItemId={casePlanData.projectQaItemId}
                projectQaCasePlanId={casePlanId}
                casePlanDetailList={casePlanDetailList}
                visible={casePlanRelCaseModalVisiable}
                onCancel={() => {
                    setCasePlanRelCaseModalVisiable(false)
                }}
                onSaveSuccess={() => {
                    setCasePlanRelCaseModalVisiable(false);
                    getCasePlanDetail();
                }}
            />

            <QaCaseDetailModal
                mode="execute"
                qaCase={selectCasePlanDetail.projectQaCase}
                visible={qaCaseDetailVisiable}
                qaCaseExecute={selectCasePlanDetail}
                onExecuteComplete={onExecuteComplete}
                onCancel={() => {
                    setQaCaseDetailVisiable(false)
                }}
            >
            </QaCaseDetailModal>
        </div>
    )
}

export default connect(({ user }) => ({
    myUserInfo: user.myInfo
}))(QaCasePlanDetal);